package com.sky.controller.common;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
@Api("通用接口")
@Slf4j
@RequestMapping("/admin/common")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws IOException {
        //日志输出一下
        log.info("上传的文件是:{}" ,file);
        String upload = null;
        try {
            //我们先获取到图片的数据类型
            String name = file.getClass().getName();
            //根据字符串分割
            int index = name.lastIndexOf(".");
            //根据指定位置获取图片文件后缀
            String substring = name.substring(index, name.length() - 1);
            //生成随机数字母,在和后缀进行拼接，得到一个全新的路径
            String newName = UUID.randomUUID() + substring;
            //根据工具类完成
            upload = aliOssUtil.upload(file.getBytes(), newName);
        } catch (IOException e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }

        return Result.success(upload);
    }
}
